package com.party.mobile.web.controller.analysis;

import com.party.common.utils.PartyCode;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.analysis.StatisticsEvent;
import com.party.core.service.analysis.IStatisticsEventService;
import com.party.mobile.biz.analysis.StatisticalAppEventBizService;
import com.party.mobile.web.dto.analysis.AppEventFlowInput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 统计app
 *
 * @author yifeng
 * @date 2018/9/13 0013
 * @time 上午 11:21
 */
@Controller
@RequestMapping("analysis/appFlow")
public class StatisticalAPPController {
    @Autowired
    private IStatisticsEventService statisticsEventService;
    @Autowired
    private StatisticalAppEventBizService statisticalAppEventBizService;

    Logger logger = LoggerFactory.getLogger(getClass());

    @ResponseBody
    @RequestMapping("innerEventFlowDataReport")
    public void innerEventFlowDataReport(AppEventFlowInput flowInput, HttpServletResponse response) throws IOException {
        if (StringUtils.isEmpty(flowInput.getDeviceId())) {
            throw new BusinessException(PartyCode.DATA_UNEXIST, "设备id为空");
        }
        if (StringUtils.isEmpty(flowInput.getPartnerId())) {
            throw new BusinessException(PartyCode.DATA_UNEXIST, "机构id为空");
        }
        if ("".equalsIgnoreCase(flowInput.getCode())) {
            throw new BusinessException(PartyCode.DATA_UNEXIST, "事件Code为空");
        }
        StatisticsEvent statisticsEvent = statisticsEventService.getByCode(flowInput.getCode());
        if (null == statisticsEvent) {
            throw new BusinessException(PartyCode.DATA_UNEXIST, "事件Code不存在");
        }
        try {
            statisticalAppEventBizService.innerEventFlowDataReport(statisticsEvent.getId(), flowInput);
        } catch (Exception e) {
            logger.error("记录app访问记录异常", e);
        } finally {
            BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR);
            ImageIO.write(image, "png", response.getOutputStream());
        }
    }
}
